package com.enrollandpay.base;

import com.enrollandpay.utils.CommonUtil;
import com.enrollandpay.utils.DateUtil;
import com.enrollandpay.utils.ResultJson;
import com.enrollandpay.utils.SubmitCheck;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import tk.mybatis.mapper.common.Mapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by 94504 on 2017/6/23.
 */

@Controller
public class BaseController
{

    // 合法的pageName
    private static final String[] pageNames = {"school", "campus", "grade", "clazz", "student", "signup", "activity", "user"};

    /**
     * 根据pageName来跳转页面, 为空时返回到首页
     *
     * @param pageName
     * @return
     */

    @RequestMapping("/gotoPage")
    public String gotoPage(String pageName,HttpServletRequest request, HttpSession session)
    {
        session.setAttribute("token", DateUtil.getNo(3));

        if (StringUtils.isBlank(pageName))
            return "index";
        else if (!ArrayUtils.contains(pageNames, pageName))
            return "index";
        else
            return "main/" +pageName;
    }


    /**
     *
     * @param param
     * @param separatorChar
     * @return
     */
    public ResultJson deleteByPrimaryKeys(String param, Character separatorChar, Mapper mapper)
    {
        ResultJson resultJson = new ResultJson();
        Integer[] ids = CommonUtil.stringToIntegerArr(param, separatorChar);
        if (ids != null)
        {
            for (Integer id : ids)
                mapper.deleteByPrimaryKey(id);

            return resultJson;
        }

        resultJson.setStatus("0");
        return resultJson;
    }

    @RequestMapping("/imgUpload")
    public @ResponseBody
    ResultJson imgUpload(HttpServletRequest request) throws IllegalStateException, IOException
    {
        String path = ""; // 文件存放的绝对路径
        String fileName = ""; // 源文件的文件名
        String url = ""; // img图片的src地址
        String dateString = ""; // 日期文件
        String newFileName = "";

        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession() .getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request))
        {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator<String> iter = multiRequest.getFileNames();

            while (iter.hasNext())
            {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null)
                {
                    fileName = new String(file.getOriginalFilename().getBytes("ISO8859-1"), "utf-8"); // 获取文件名
                    // 获取文件扩展名
                    String filenameExtension = fileName.substring(fileName.lastIndexOf("."));
                    // newFileName = DateUtil.getNo(6) + "_" + fileName;
                    newFileName = DateUtil.getNo(6) + filenameExtension;
                    dateString = DateUtil.getNowMonthString();
                    path = request.getSession().getServletContext().getRealPath("\\imgUpload") + "\\" + dateString;// 获取服务器路径

                    File pathFile = new File(path);
                    if (!pathFile.exists())
                    {
                        pathFile.mkdirs();
                    }
                    // 上传
                    file.transferTo(new File(path + "/" + newFileName));
                }

            }

        }

        ResultJson resultJson = new ResultJson();
        url = request.getContextPath() + "/imgUpload/" + dateString + "/" + newFileName;
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        map.put("fileName", fileName);
        resultJson.setData(map);

        return resultJson;
    }

}
